package com.shengqi.xinnongren.work.ui.goods.activities;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.dialog.ChooseItemDialog;
import com.shengqi.xinnongren.work.ui.goods.adapter.OrderGoodsAdapter;
import com.shengqi.xinnongren.work.ui.goods.presenter.ConfirmOrder2Presenter;
import com.shengqi.xinnongren.work.ui.goods.view.ConfirmOrderView2;
import com.shengqi.xinnongren.work.ui.home.model.CartGoodsBean;
import com.shengqi.xinnongren.work.ui.user.activities.AddressActivity;
import com.shengqi.xinnongren.work.ui.user.activities.ToBeVipActivity;
import com.shengqi.xinnongren.work.ui.user.model.AddressBean;
import com.shengqi.xinnongren.work.ui.user.model.CouponBean;
import com.shengqi.xinnongren.work.ui.user.model.PrepareOrderInfoBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提交订单
 */
public class ConfirmOrderActivity2 extends BaseMvpActivity<ConfirmOrderView2, ConfirmOrder2Presenter> implements ConfirmOrderView2, ChooseItemDialog.Builder.OnItemClickListener {

    private static final String EXTRA_COM_ID = "comid";
    private static final int CHOOSE_ADDRESS_CODE = 0x111;

    @BindView(R.id.sr_refresh)
    SwipeRefreshLayout mRefreshLayout;

    @BindView(R.id.rv_choose_coupon)
    RecyclerView mRvChooseCoupon;
    @BindView(R.id.rv_order_goods)
    RecyclerView mRvOrderGoods;

    //地址
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    //地址信息
    @BindView(R.id.tv_address_info)
    TextView mTvAddressInfo;

    //配送时间
    @BindView(R.id.tv_send_time)
    TextView mTvSendTime;
    //店铺名称
    @BindView(R.id.tv_store_name)
    TextView mTvStoreName;
    //商品金额
    @BindView(R.id.tv_goods_money)
    TextView mTvGoodsMoney;
    //配送费
    @BindView(R.id.tv_send_fee)
    TextView mTvSendFee;
    //积分抵扣
    @BindView(R.id.tv_integral)
    TextView mTvIntegral;
    //优惠券
    @BindView(R.id.tv_coupon_money)
    TextView mTvCouponMoney;
    //满减价格
    @BindView(R.id.tv_full_reduction_money)
    TextView mTvFullReductionMoney;
    //优惠券优惠金额
    @BindView(R.id.tv_integral_money)
    TextView mTvIntegralMoney;

    //金额信息
    @BindView(R.id.tv_money_info)
    TextView mTvMoneyInfo;
    //实付金额
    @BindView(R.id.tv_pay_money)
    TextView mTvPayMoney;

    @BindView(R.id.ll_buy_vip_container)
    LinearLayout mLlBuyVipContainer;
    @BindView(R.id.ll_address_container)
    LinearLayout mLlAddressContainer;

    @BindView(R.id.cb_use_integral)
    CheckBox mCbUseIntegral;

    @BindView(R.id.et_remark)
    EditText mEtRemark;

    private String mComId;
    private String mCouponId;
    private int mUseIntegral;

    private PrepareOrderInfoBean mPrepareOrderInfoBean;
    private List<PrepareOrderInfoBean.DeliveryTimeBean> mDeliveryTimeList = new ArrayList<>();
    private PrepareOrderInfoBean.DeliveryTimeBean mCurrentTimeBean;
    private AddressBean mCurrentAddressBean;
    private List<CartGoodsBean> mCartGoodsList = new ArrayList<>();
    private List<CouponBean> mCouponBeanList = new ArrayList<>();
    private OrderGoodsAdapter mOrderGoodsAdapter;
    private ChooseCouponAdapter mChooseCouponAdapter;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_confirm_order2;
    }

    public static void start(Context context, String comId) {
        context.startActivity(new Intent(context, ConfirmOrderActivity2.class).putExtra(EXTRA_COM_ID, comId));
    }

    @Override
    protected ConfirmOrder2Presenter createPresenter() {
        return new ConfirmOrder2Presenter();
    }

    @Override
    protected void initView() {
        mComId = getIntent().getStringExtra(EXTRA_COM_ID);
        mRefreshLayout.setOnRefreshListener(this::getData);
        mCbUseIntegral.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mUseIntegral = isChecked ? 1 : 0;
            ToastHelper.getInstance(ConfirmOrderActivity2.this).showNormal(String.format("%s使用积分抵扣", isChecked ? "" : "不"));
            getData();
        });
    }

    @Override
    protected void initData() {
        mChooseCouponAdapter = new ChooseCouponAdapter();
        mChooseCouponAdapter.setOnItemCheckedListener(position -> {
            if (position < 0)
                mCouponId = "";
            else
                mCouponId = mCouponBeanList.get(position).couponId;
            getData();
        });
        mRvChooseCoupon.setAdapter(mChooseCouponAdapter);
        mRvChooseCoupon.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mOrderGoodsAdapter = new OrderGoodsAdapter(this, mCartGoodsList);
        mRvOrderGoods.setAdapter(mOrderGoodsAdapter);
        mRvOrderGoods.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        getData();
    }

    private void getData() {
        mPresenter.getPrepareOrderInfo(mComId, mCouponId, mUseIntegral);
    }

    private void resetRefreshLayout() {
        mRefreshLayout.setRefreshing(false);
    }

    /**
     * 选择送货时间
     */
    @OnClick(R.id.ll_choose_time)
    void ll_choose_time() {
        if (mDeliveryTimeList.size() == 0) {
            return;
        }
        ArrayList<String> stringList = new ArrayList<>();
        for (PrepareOrderInfoBean.DeliveryTimeBean deliveryTimeBean : mDeliveryTimeList) {
            stringList.add(String.format("%s #%s ",deliveryTimeBean.getTime(),deliveryTimeBean.getIsFull()));
        }
        new ChooseItemDialog.Builder(this)
                .setStringList(stringList)
                .setOnItemClickListener(this)
                .build()
                .show();
    }

    /**
     * 选择收货地址
     */
    @OnClick(R.id.ll_address_container)
    void ll_address_container() {
        AddressActivity.startForResult(this, true, CHOOSE_ADDRESS_CODE);
    }

    /**
     * 开通vip
     */
    @OnClick(R.id.tv_buy_vip)
    void tv_buy_vip() {
        startActivity(new Intent(this, ToBeVipActivity.class));
    }

    /**
     * 确认订单
     */
    @OnClick(R.id.btn_confirm_order)
    void btn_confirm_order() {
        if (mCurrentAddressBean == null) {
            ToastHelper.getInstance(this).showWarn("请选择收货地址");
            return;
        }
        if (mCurrentTimeBean == null) {
            ToastHelper.getInstance(this).showWarn("请选择送货时间");
            return;
        }
        mPresenter.commitOrder(
                mCurrentAddressBean.addressId,
                mComId,
                mCurrentTimeBean.getTimeId(),
                mCouponId,
                mUseIntegral,
                mEtRemark.getText().toString()
        );
    }


    @Override
    public void onItemClick(ChooseItemDialog dialog, int position) {
        dialog.dismiss();
        mCurrentTimeBean = mDeliveryTimeList.get(position);
        updateDisplay();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
        resetRefreshLayout();
    }

    @Override
    public void onGetPrepareOrderInfo(PrepareOrderInfoBean prepareOrderInfoBean) {
        resetRefreshLayout();
        mPrepareOrderInfoBean = prepareOrderInfoBean;

        if (mCurrentAddressBean == null)
            mCurrentAddressBean = prepareOrderInfoBean.getApiAddress();

        //送货时间列表相关
        mDeliveryTimeList.clear();
        mDeliveryTimeList.addAll(mPrepareOrderInfoBean.getDeliveryTime());
//        if (mDeliveryTimeList.size() > 0) {
//            mCurrentTimeBean = mDeliveryTimeList.get(0);
//        }

        //商品列表相关
        mCartGoodsList.clear();
        mCartGoodsList.addAll(mPrepareOrderInfoBean.getApiComSkuCom());
        mOrderGoodsAdapter.notifyDataSetChanged();

        //优惠券列表相关
        mCouponBeanList.clear();
        mCouponBeanList.addAll(mPrepareOrderInfoBean.getCoupon());
        mChooseCouponAdapter.notifyDataSetChanged();
        checkSelectedCouponIsExist();

        updateDisplay();
    }

    /**
     * 此方法目的在重新获取订单信息后，
     * 检查当前选中的优惠券id是否存在，
     * 如存在恢复优惠券列表的选中效果，
     * 不存在则清除选中的id和选中效果。
     */
    private void checkSelectedCouponIsExist() {
        if (TextUtils.isEmpty(mCouponId)) return;
        if (mCartGoodsList.size() == 0) {
            mCouponId = null;
            return;
        }
        for (int i = 0; i < mCouponBeanList.size(); i++) {
            if (mCouponBeanList.get(i).couponId.equals(mCouponId)) {
                mChooseCouponAdapter.setCurChosePosition(i);
                return;
            }
        }
        mChooseCouponAdapter.resetChoose();
    }

    @Override
    public void onOrderCommit(String orderId, String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        ChoosePayTypeActivity.start(this, orderId);
        finish();
    }

    /**
     * 更新界面显示相关
     */
    private void updateDisplay() {
        //更新地址显示
        if (mCurrentAddressBean != null) {
            mTvAddress.setText(String.format("%s%s%s%s", mCurrentAddressBean.province, mCurrentAddressBean.city, mCurrentAddressBean.county, mCurrentAddressBean.address));
            mTvAddressInfo.setText(String.format("%s   %s", mCurrentAddressBean.name, mCurrentAddressBean.mobile));
        } else {
            mTvAddress.setText("未设置默认地址");
            mTvAddressInfo.setText("点击选择或创建");
        }
        //更新送货时间显示
        if (mCurrentTimeBean != null) {
            mTvSendTime.setText(mCurrentTimeBean.getTime());
        }
        //更新订单信息显示
        if (mPrepareOrderInfoBean != null) {
            mLlBuyVipContainer.setVisibility(mPrepareOrderInfoBean.getIsVip() == 1 ? View.GONE : View.VISIBLE);
            mTvStoreName.setText("新农人");
            mTvGoodsMoney.setText(String.format("￥%s", mPrepareOrderInfoBean.getComMoney()));
            mTvSendFee.setText(String.format("￥%s", mPrepareOrderInfoBean.getShippingFee()));
            mTvIntegral.setText(String.format("%s积分", mPrepareOrderInfoBean.getIntegral()));
            mTvCouponMoney.setText(String.format("-￥%s", mPrepareOrderInfoBean.getCouponAmount()));
            mTvFullReductionMoney.setText(String.format("-￥%s", mPrepareOrderInfoBean.getFullReduction()));
            mTvIntegralMoney.setText(String.format("-￥%s", mPrepareOrderInfoBean.getIntegralMoney()));
            mTvMoneyInfo.setText(String.format("共%s件 已优惠￥%s", mPrepareOrderInfoBean.getComNum(), mPrepareOrderInfoBean.getDiscountAmount()));
            mTvPayMoney.setText(String.format("￥%s", mPrepareOrderInfoBean.getOrderPrice()));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //选址地址之后的回调
                case CHOOSE_ADDRESS_CODE:
                    Serializable serializable = data.getSerializableExtra("data");
                    if (serializable == null) return;
                    mCurrentAddressBean = (AddressBean) serializable;
                    updateDisplay();
                    break;
            }
        }
    }


    /**
     * 选择优惠券adapter
     */
    class ChooseCouponAdapter extends RecyclerView.Adapter<ChooseCouponAdapter.Holder> {

        private int mCurChosePosition = -1;
        private OnItemClickListener mOnItemClickListener;

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(LayoutInflater.from(ConfirmOrderActivity2.this).inflate(R.layout.item_order_choose_coupon, parent, false));
            holder.itemView.setOnClickListener(v -> {
                if (mCurChosePosition == holder.getAdapterPosition())
                    mCurChosePosition = -1;
                else
                    mCurChosePosition = holder.getAdapterPosition();
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(holder.getAdapterPosition());
                }
                notifyDataSetChanged();
            });
            return holder;
        }

        public void setOnItemCheckedListener(OnItemClickListener onItemClickListener) {
            mOnItemClickListener = onItemClickListener;
        }

        public int getCurChosePosition() {
            return mCurChosePosition;
        }

        public void setCurChosePosition(int curChosePosition) {
            mCurChosePosition = curChosePosition;
            notifyDataSetChanged();
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            if (position == mCurChosePosition) {
                holder.vCheckedIcon.setVisibility(View.VISIBLE);
                holder.llCouponContainer.setBackgroundResource(R.drawable.bg_order_choose_coupon_selected);
                holder.vCircleIcon.setBackgroundResource(R.drawable.bg_order_choose_coupon_circle);
            } else {
                holder.vCheckedIcon.setVisibility(View.GONE);
                holder.llCouponContainer.setBackgroundResource(R.drawable.bg_order_choose_coupon_normal);
                holder.vCircleIcon.setBackgroundResource(R.drawable.bg_order_choose_coupon_circle_gray);
            }
            if (position == 1) {
                holder.tvMostCheap.setVisibility(View.VISIBLE);
            } else {
                holder.tvMostCheap.setVisibility(View.GONE);
            }

            CouponBean couponBean = mCouponBeanList.get(position);
            holder.tvYuan.setText(String.format("%s元", couponBean.discountAmount));
            holder.tvTitle.setText(couponBean.name);
            holder.tvDesc.setText(String.format("%s 满%s元可用", couponBean.remarks, couponBean.useAmount));
            holder.tvTime.setText(couponBean.time);
        }

        @Override
        public int getItemCount() {
            return mCouponBeanList.size();
        }

        public void resetChoose() {
            setCurChosePosition(-1);
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.v_check)
            View vCheckedIcon;
            @BindView(R.id.v_circle)
            View vCircleIcon;
            @BindView(R.id.ll_coupon_container)
            LinearLayout llCouponContainer;
            @BindView(R.id.tv_most_cheap)
            TextView tvMostCheap;

            @BindView(R.id.tv_yuan)
            TextView tvYuan;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_desc)
            TextView tvDesc;
            @BindView(R.id.tv_time)
            TextView tvTime;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }
}
